package com.example.springmvcproject.Controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.example.springmvcproject.Utils.ResultCode;
import com.example.springmvcproject.Utils.ResultMessage;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.Objects;

@RestControllerAdvice
@Log4j2
public class GlobalExceptionHandler {

    @ExceptionHandler({NotLoginException.class})
    public ResultMessage handlerNotLoginException(NotLoginException nle)
            throws Exception {
        // 打印堆栈，以供调试

        // 判断场景值，定制化异常信息
        String error = "";
        if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            error = "未提供token";
        }
        else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            error = "token无效";
        }
        else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            error = "token已过期";
        }
        else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
            error = "token已被顶下线";
        }
        else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
            error = "token已被踢下线";
        }
        else {
            error = "当前会话未登录";
        }
        // 返回给前端
        return new ResultMessage(ResultCode.RESULT_LOGIN.getCode(), ResultCode.RESULT_LOGIN.getStatus(),error,null);
    }

    //处理全局异常
    @ExceptionHandler(Exception.class)
    public ResultMessage handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResultMessage(ResultCode.RESULT_EXCEPTION.getCode(), ResultCode.RESULT_EXCEPTION.getStatus(), "系统繁忙,请稍后再试",null);
    }
    //参数传输一异常
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultMessage handleBindException(MethodArgumentNotValidException e) {
        //log.error(e.getMessage(), e);
        return new ResultMessage(ResultCode.RESULT_PARAMS.getCode(), ResultCode.RESULT_PARAMS.getStatus(), Objects.requireNonNull(e.getFieldError()).getDefaultMessage(),null);
    }

    //全局权限异常
    @ExceptionHandler({NotRoleException.class})
    public ResultMessage handleNotRoleException(NotRoleException e) {
        return new ResultMessage(ResultCode.RESULT_ROLE.getCode(), ResultCode.RESULT_ROLE.getStatus(), "您暂无权限登录本页面",null);
    }

    //404异常
    @ExceptionHandler({NoHandlerFoundException.class})
    public ResultMessage handleNoHandlerFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResultMessage(3, 404,"您访问的URL不存在",null);
    }
}
